import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: "",
    name: '',
    avatar: '',
    accountId: "",
    menuList: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ACCOUNTID: (state, id) => {
    state.accountId = id
  },
  SET_MENU: (state, list) => {
    state.menuList = list
  }
}


const getMenuAuth = (list = []) =>  {
  return list.map((item, index) => {
    // console.log("item", item)
    let children = []
    if (item.childResources && item.childResources.length) {
      children = getMenuAuth(item.childResources)
    }
    return {
      path: item.path || "/",
      name: item.resourceName,
      children
    }
  })
}

const actions = {
  // user login
  setLoginInfo({ commit }, data) {
    commit('SET_TOKEN', data.token)
    commit("SET_NAME", data.loginName)
    commit("SET_ACCOUNTID", data.tokenId)
    // let menuList = getMenuAuth(data.menuList)
    // console.log('getMenuAuth', menuList)
    commit("SET_MENU", data.menuList)
  },
  logOutStatus({ commit }) {
    commit('SET_TOKEN', "")
    commit("SET_NAME", "")
    commit("SET_ACCOUNTID", "")
    commit("SET_MENU", "")
    resetRouter()
    console.log("清除成功")
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

